//
//  WWShopCarManager.m
//  Shopping
//
//  Created by 张世敏 on 16/8/23.
//  Copyright © 2016年 张湾湾. All rights reserved.
//

#import "WWShopCarManager.h"
#import "WWRightCellModel.h"


@interface WWShopCarManager()

// 购物车中的商品
@property (nonatomic, strong) NSMutableArray<WWRightCellModel *> *rightCellModelList;

@end

@implementation WWShopCarManager

Singleton_m(WWShopCarManager)

/** 对外访问实例 **/
+(instancetype)sharedShopCarManager{
    
    return [self sharedWWShopCarManager];
}


/** 添加商品到购物车 **/
-(void)addSupermarketGoodsToShopCar:(WWRightCellModel *)rightModel{
    // 先遍历购物车商品,避免添加重复商品
    for (WWRightCellModel *innerGoods in self.rightCellModelList) {
        if (innerGoods.id == rightModel.id) {
            innerGoods.userBuyCount += 1;
            return;
        }
    }
    
    // 第一次添加,初始化为1
    rightModel.userBuyCount = 1;
    [self.rightCellModelList addObject:rightModel];
}


/** 从购物车中移除商品 **/
-(void)removeSupermarketGoodsFromShopCar:(WWRightCellModel *)rightModel{
    // 需要判断当前购物车中对应商品是否存在(只能通过比较商品id),如果存在,发出通知,让rightModel的辅助属性(购物车中商品的数量)-1
    for (int i = 0; i < self.rightCellModelList.count; i++) {
        WWRightCellModel *innerModel = self.rightCellModelList[i];
        
        if (innerModel.id == rightModel.id) {
            NSInteger userBuyCount = innerModel.userBuyCount; // 当前商品的购买数量
            if (userBuyCount == 1) {
                [self.rightCellModelList removeObjectAtIndex:i];
            } else {
                innerModel.userBuyCount -= 1;
            }
            
            return;
        }
    }
}


/** 获取购物车中的所有商品 **/
-(NSMutableArray<WWRightCellModel *> *)getShopCarGoodsList{
    
    return self.rightCellModelList;
}


/** 判断购物车里的商品是否为空 **/
-(BOOL)isEmpty{
    
    return self.rightCellModelList.count == 0;
}


/** 获取购物车中商品种类的数量 **/
-(NSInteger)getShopCarGoodsCategoriesCount{
    
    return self.rightCellModelList.count;
}


/** 获取购物车中商品的总数量 **/
-(NSInteger)getShopCarGoodsCount{
    
    NSInteger totalCount = 0;
    for (WWRightCellModel *innerModel in self.rightCellModelList) {
        totalCount += innerModel.userBuyCount;
    }
    
    return totalCount;
}


/** 获取购物车中商品的总价格 **/
-(CGFloat)getTotalPriceOfShopCarGoods{
    CGFloat totalPrice = 0;
    for (WWRightCellModel *innerModel in self.rightCellModelList) {
        totalPrice += innerModel.price.floatValue * innerModel.userBuyCount;
    }
    
    return totalPrice;
}


#pragma mark - 懒加载
-(NSMutableArray<WWRightCellModel *> *)rightCellModelList{
    if (_rightCellModelList == nil) {
        _rightCellModelList = [NSMutableArray array];
    }
    
    return _rightCellModelList;
}

@end
